<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2018/11/20
 * Time: 19:30
 */
namespace common\logics\taobao;

use common\widgets\PhpExcel;
use common\widgets\Request;
use common\widgets\Tool;
use yii\base\BaseObject;
use Yii;

class TaoBaoLogic extends BaseObject implements ITaoBao
{
    /** @var \common\sources\write\taobao\TaoBaoAccess $WTaoBaoAccess */
    private $WTaoBaoAccess;
    /** @var \common\sources\read\taobao\TaoBaoAccess $RTaoBaoAccess */
    private $RTaoBaoAccess;
    /** @var  \common\sources\read\message\MesgAccess  $RMesgAccess */
    private $RMesgAccess;
    /** @var \common\sources\write\message\MesgAccess  $WMesgAcdess */
    private $WMesgAcdess;
    /** @var \common\sources\read\sendddcode\SendDdCodeAccess $RSendDdCodeAccess **/
    private $RSendDdCodeAccess;
    /** @var \common\sources\write\sendddcode\SendDdCodeAccess $WSendDdCodeAccess **/
    private $WSendDdCodeAccess;
    /** @var \common\sources\read\buyuser\BuyUserAccess $RBuyUserAccess **/
    private $RBuyUserAccess;
    /** @var \common\sources\read\classifyreason\ClassifyReasonAccess $RClassifyReasonAccess */
    private $RClassifyReasonAccess;

    public function init()
    {
        $this->WTaoBaoAccess = Yii::$container->get('WTaoBaoAccess');
        $this->RTaoBaoAccess = Yii::$container->get('RTaoBaoAccess');
        $this->RMesgAccess = Yii::$container->get('RMesgAccess');
        $this->WMesgAcdess = Yii::$container->get('WMesgAccess');
        $this->RSendDdCodeAccess = Yii::$container->get('RSendDdCodeAccess');
        $this->WSendDdCodeAccess = Yii::$container->get('WSendDdCodeAccess');
        $this->RBuyUserAccess = Yii::$container->get('RBuyUserAccess');
        $this->RClassifyReasonAccess = Yii::$container->get('RClassifyReasonAccess');
        parent::init(); // TODO: Change the autogenerated stub
    }

    public function verify($data)
    {
        if(empty($data['t_id'])){
            return Tool::returnJson([],401,"买号绑定id不能为空");
        }
        if(empty($data['audit_status'])){
            return Tool::returnJson([],402,"买号绑定不能为空");
        }
        //修改操作
        $result = $this->WTaoBaoAccess->verifyTaoBao($data);
        if($result){
            return Tool::returnJson([],200,"审核成功");
        }
        return Tool::returnJson([],405,"审核失败");
    }


    // 买手审核
	public function newGetTaoBaoList($data) {
		if (1 == $data['plat']) {//淘宝

			$where = ' 1=1 ';
			// 条件组装
			if (!empty($data['audit_status']) && in_array($data['audit_status'],[1,2,3])) {
				$where = ' t.audit_status = ' . $data['audit_status']; //状态
			}
			//冻结自定义吗
			if (!empty($data['audit_status']) && in_array($data['audit_status'],[10])) {
				$where = ' t.freeze = 1' ; //状态
			}

			if ($data['search_type'] == 1 && !empty($data['key'])) {//会员ID'
				$where = ' u.phone = ' . $data['key'];

			} elseif ($data['search_type'] == 2 && !empty($data['key'])) {//绑定买号
				$where = ' t.tbname = "' . $data['key'].'"';

			} elseif ($data['search_type'] == 3 && !empty($data['key'])) {//收件人姓名
				$where = ' t.takename = "' . $data['key'].'"';

			} elseif ($data['search_type'] == 4 && !empty($data['key'])) {//收件人手机号'
				$where = ' t.takephone = "' . $data['key'].'"';

			} elseif ($data['search_type'] == 5 && !empty($data['key'])) {//街道地址
				$where = ' t.addr = "' . $data['key'].'"';

			} elseif ($data['search_type'] == 6 && !empty($data['key'])) {//支付宝姓名
				$where = ' t.zfbname = "' . $data['key'].'"';
			}

			// 查询数据
			$list = $this->RTaoBaoAccess->getTaoBaoGroupBy($where,$data);
			if (isset($list['list'])) {
				foreach ($list['list'] as &$val) {
					$where = [
						'buy_id' => $val['buy_id'],
					];
					// 买号列表
					$val['buy_number_list'] = [];
					$buy_number_list        = $this->RTaoBaoAccess->getBuyTaoBaoList($where);
					if ($buy_number_list) {
						foreach ($buy_number_list as $k => $value) {
							$buy_number_list[$k]['create_time'] = empty($value['create_time']) ? '' : date("Y-m-d H:i:s", $value['create_time']);
							$buy_number_list[$k]['freeze_time'] = empty($value['freeze_time']) ? '' : date("Y-m-d H:i:s", $value['freeze_time']);
							$buy_number_list[$k]['thaw_time']   = empty($value['thaw_time']) ? '' : date("Y-m-d H:i:s", $value['thaw_time']);
							//不通过原因
							if (3 == $value['audit_status']) {
								if (!empty($value['reason'])) {
									$reasonId                      = explode(',', $value['reason']);
									$buy_number_list[$k]['reason'] = $this->RClassifyReasonAccess->getReason($reasonId);
								}
							}
						}
					}
					$val['buy_number_list'] = $buy_number_list;
				}
				unset($val);
			}

		} else {//其它平台
			$count = 0;
			//根据条件搜索买号列表
			$list = [];
		}

		return Tool::returnJson([
			"list"     => $list['list'],
			"page_num" => $list['page_num'],
			"limit"    => $data['limit'],
			"count"    => $list['count'],
		], 200, "成功");
	}


	/**  已弃用
	 * @author 中崋 (1291713293@qq.com)
	 * @date   2019/5/9
	 * @return false|string
	 */
		public function getTaoBaoList($data) {
		if (1 == $data['plat']) {//淘宝
			//$count = $this->RTaoBaoAccess->countTaoBaoList($data);
			//根据条件搜索买号列表
			$list = $this->RTaoBaoAccess->getTaoBaoList($data);
			if ($list['list']) {
				foreach ($list['list'] as &$value) {
					$value['UserPhone']   = $this->RBuyUserAccess->getBuyUserInfo($value['buy_id'])['phone'];
					$value['create_time'] = empty($value['create_time']) ? '' : date("Y-m-d H:i:s", $value['create_time']);
					$value['freeze_time'] = empty($value['freeze_time']) ? '' : date("Y-m-d H:i:s", $value['freeze_time']);
					//不通过原因
					if (3 == $value['audit_status']) {
						if (!empty($value['reason'])) {
							$reasonId        = explode(',', $value['reason']);
							$value['reason'] = $this->RClassifyReasonAccess->getReason($reasonId);
						}
					}
				}
				unset($value);
			}
		} else {//其它平台
			$count = 0;
			//根据条件搜索买号列表
			$list = [];
		}
		return Tool::returnJson([
			"list"     => $list['list'],
			"page_num" => $data['page_num'],
			"limit"    => $data['limit'],
			"count"    => $list['count'],
		], 200, "成功");
	}

	//买号、冻结解冻
	public function Freeze($data) {
		if (empty($data['id'])) {
			return Tool::returnJson([], 401, "买号绑定id不能为空");
		}
		if (empty($data['freeze'])) {
			return Tool::returnJson([], 401, "请点击操作");
		}

		$result    = false;
		$pass_text = '';//1-冻结 2-解冻
		// 校验 买号
		$info = $this->RTaoBaoAccess->getTaoBaoByTid($data['id']);
		if (empty($info)) {
			return Tool::returnJson([], 401, "买号不存在");
		}

		if (1 == $data['freeze']) {
			$pass_text = '冻结';
		} else if (2 == $data['freeze']) {
			$pass_text           = '解冻';
			$data['freeze_time'] = null;
			$data['thaw_time']   = time();
		}
		$result    = $this->WTaoBaoAccess->thawFreeze($data);

		if ($result == true) {
			return Tool::returnJson([], 200, $pass_text . "成功");
		}
		return Tool::returnJson([], 405, $pass_text . "失败！");
	}

    public function Remark($data) {
        if (empty($data['t_id'])) {
            return Tool::returnJson([],401,"买号绑定id不能为空");
        }
        if (empty($data['remark'])) {
            return Tool::returnJson([],401,"请输入备注类容");
        }
        if (empty($data['remarkUser'])) {
            return Tool::returnJson([],401,"备注人不能为空");
        }
        $result =  $this->WTaoBaoAccess->Remark($data);
        if ($result) {
            return Tool::returnJson([],200,"成功");
        }
        return Tool::returnJson([],405,"失败");
    }

    public function batchFreeze($data) {
        if(empty($data['operator'])){
            return Tool::returnJson([],402,"操作人不能为空");
        }
        //增加钉钉验证码=验证
        if(empty($data['sys_code'])){
            return Tool::returnJson([],402,"请填写验证码");
        }
        if(empty($data['phone'])){
            return Tool::returnJson([],401,"操作人手机号不能为空");
        }
        $smsArr = $this->RSendDdCodeAccess->getSendCode($data);
        if (intval($smsArr['code']) !== intval($data['sys_code'])) {
            return Tool::returnJson($data = [], $code = 405, '验证码输入有误');
        }
        //删除钉钉验证码
        $this->WSendDdCodeAccess->delDdCodeById($smsArr['id']);
        $data['reason'] = '批量冻结操作';
        $data['pass'] = 1;//冻结
        $data['freezeUser'] = $data['operator'];
        set_time_limit(0);
        if (isset($_FILES['file']) && 0 == $_FILES['file']['error']) {
            $title = $_FILES['file']['name'];
            $tmp = explode('.',$title);
            $fix = end($tmp);
            if (!in_array($fix,['xls','csv','xlsx'])) {
                return Tool::returnJson([],403,"请上传excel文件");
            }
            $file = $_FILES['file']['tmp_name'];
            $datas = PhpExcel::readExcel($file);
            unset($datas[1]);
            if (count($datas) > 100)
            {
                return Tool::returnJson([],405,"上传账号信息过多");
            }
            if (count($datas) > 0) {
                $transaction = Yii::$app->db->beginTransaction();
                try{
                    foreach ($datas as $value) {
                        $data['buy_id'] = isset($this->RBuyUserAccess->getBuyUser(trim($value[0]))['id']) ? $this->RBuyUserAccess->getBuyUser(trim($value[0]))['id'] : '';
                        $data['tbname'] = trim($value[1]);
                        if (!empty($data['buy_id'])) {
                            //冻结买号
                            $this->WTaoBaoAccess->batchFreeze($data);
                        }
                        usleep(10000);
                    }

                    $transaction->commit();
                    return Tool::returnJson([],200,"成功");
                }catch (\Exception $e) {
                    $transaction->rollBack();
                    return Tool::returnJson([],6000,"操作异常".$e->getMessage());
                }
            }
            return Tool::returnJson([],409,"上传文件内容不能为空");
        }
        return Tool::returnJson([],408,"上传文件失败");
    }
}